package com.bretagne5.radio.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.provider.Settings.Secure;
import android.util.Log;

public class Tools {
	
	public static byte[] compressToGzip(String string) throws IOException {
	    ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
	    GZIPOutputStream gos = new GZIPOutputStream(os);
	    gos.write(string.getBytes());
	    gos.close();
	    byte[] compressed = os.toByteArray();
	    os.close();
	    return compressed;
	}

	/**
	 * Check if an internet connection is available
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		return (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected());
	}
	
	/**
	 * 
	 * @param context
	 * @return String : the application version
	 */
	public static String getAppVersion(Context context){
		
		String appli_version ;
	
		try {
			appli_version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			appli_version = "none";
		}
		if(appli_version == null) 
			appli_version = "none";
		
		return appli_version;
	}
	
	/**
	 * 
	 * @param context
	 * @return int : the application version
	 */
	public static int getAppVersionInt(Context context) {
	    try {
	        PackageInfo packageInfo = context.getPackageManager()
	                .getPackageInfo(context.getPackageName(), 0);
	        return packageInfo.versionCode;
	    } catch (NameNotFoundException e) {
	        // should never happen
	        throw new RuntimeException("Could not get package name: " + e);
	    }
	}
	
	public static String getDeviceId(Context context){
		
		return Secure.getString(context.getContentResolver(),Secure.ANDROID_ID);
		
	}
	
	/**
	 * 
	 * @param androidPermission : the name permission to check
	 * @param context
	 * @return true if permission is set in manifest.xml
	 */
	public static boolean checkPermissionIsSet(String androidPermission, Context context)
	{
	    int res = context.checkCallingOrSelfPermission(androidPermission);
	    
	    if (res == PackageManager.PERMISSION_GRANTED)
	    	return true ;
	    
	    else {
	    	
	    	Log.w("Appehour", androidPermission +" is not set");
	    	return false;
	    	
	    }   
	}
}
